<?php
class Module_Impl_Acl implements Module_Interface_Acl{
	/**
     * $_actionController
     *
     * @var Zend_Acl
     */
	protected $_acl_roles ;
	/**
     * $_actionController
     *
     * @var Zend_Controller_Action
     */
    protected $_actionController = null;
	/**
   * @var Zend_Db_Adapter_Pdo_Mysql
   */
	protected $_dbAdapter = null;
	/**
	 * Singleton instance
	 * @var Module_Acl
	 */
	protected static $_instance = null;
	protected function __construct(){
		try{		
			if(empty($this->_dbAdapter)){
				$this->_dbAdapter = Zend_Db_Table::getDefaultAdapter();
			}			
		}catch (Exception $e){
			throw $e;
		}
		if(empty($this->_dbAdapter) or !$this->_dbAdapter instanceof Zend_Db_Adapter_Abstract){
			throw new Exception('dbAdapter is wrong.');
		}		
	}
	/**
	 * Singleton instance 
	 * @return Module_Acl
	 */
	public static function getInstance() {
		if (null === self::$_instance) {
			self::$_instance = new self ( );
		}
		return self::$_instance;
	}
	
	public function setActionController(Zend_Controller_Action $actionController = null) {
        $this->_actionController = $actionController;
        return $this;
    }
	 /**
     * Return the Request object
     *
     * @param Zend_Controller_Action
     */
	public function isAllow($id,$resouce_name){
		$this->initRoles();	
		$this->initSources();
		if($this->_acl_roles->has($resouce_name)){
			return $this->_acl_roles->isAllowed($id,$resouce_name);		
		}
		return false;
	}
	
	protected function initRoles(){
		$sqlArray ['tablename'] = Config_Table::TABLE_ACL_ROLE;
		$mysqlDb = DbOperation_Select::getInstance();
		$roles = $mysqlDb->getData($sqlArray);
		$this->_acl_roles = new Zend_Acl();
		foreach ($roles as $role){
			$inherit_id = (int)$role['inherit_id'];
			$role_id = (int)$role['id'];
			if($inherit_id === $role_id){
				$this->_acl_roles->addRole(new Zend_Acl_Role($role_id));
			}else{
				$this->_acl_roles->addRole(new Zend_Acl_Role($role_id),$inherit_id);
			}
		}		
	}
	protected function initSources(){
		$sqlArray ['tablename'] = Config_Table::TABLE_ACL_RESOURCE;
		$mysqlDb = DbOperation_Select::getInstance();
		$resources = $mysqlDb->getData($sqlArray);
		foreach ($resources as $resource){
			$resouce_name = $resource['module'].'/'.$resource['controller'].'/'.$resource['action'];
			$acl_resource = new Zend_Acl_Resource($resouce_name);
			$this->_acl_roles->add($acl_resource);
			$this->_acl_roles->allow($resource['role_id'],$acl_resource);			
		}		
	}
}
